from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (QWidget, QListWidget, QListWidgetItem, QVBoxLayout)


class LeftMenu(QWidget):
    """左侧菜单栏组件，支持动态调整宽度和菜单项点击事件"""
    menuItemClicked = pyqtSignal(int)  # 菜单项点击信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self.setup_menu_items()

    def init_ui(self):
        """初始化UI布局和样式"""
        # 设置最小/最大宽度
        self.setMinimumWidth(80)
        self.setMaximumWidth(120)

        # 主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # 创建菜单列表控件
        self.menu_list = QListWidget()
        self.menu_list.setFocusPolicy(Qt.NoFocus)  # 移除选中虚线框
        self.apply_menu_styles()
        layout.addWidget(self.menu_list)

    def setup_menu_items(self):
        """添加菜单项"""
        menu_items = [
            ("🏠 首页", 0),
            ("📊 报表", 1),
            ("⚙️ 设置", 2),
            ("👥 用户", 3),
            ("❓ 帮助", 4),
            ("📝 待办", 5)
        ]

        for text, index in menu_items:
            item = QListWidgetItem(text)
            item.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            item.setData(Qt.UserRole, index)  # 存储索引数据
            self.menu_list.addItem(item)

        # 连接菜单项点击信号
        self.menu_list.itemClicked.connect(self.handle_item_click)

    def apply_menu_styles(self):
        """应用菜单样式表"""
        self.menu_list.setStyleSheet("""
            QListWidget {
                background: transparent;
                border: none;
                color: #3d3b3b;
                font-size: 14px;
                font-weight: bold;
            }
            QListWidget::item {
                height: 60px;
                padding-left: 15px;
                border-bottom: 1px solid rgba(52, 152, 219, 0.3);
            }
            QListWidget::item:selected {
                background-color: #7d8f7d;
                color: white;
                border-left: 3px solid #3498db;
            }
            QListWidget::item:hover {
                background-color: #e8f4fc;
            }
        """)

    def handle_item_click(self, item):
        """处理菜单项点击事件"""
        page_index = item.data(Qt.UserRole)
        self.menuItemClicked.emit(page_index)  # 发射点击信号

    def set_current_index(self, index):
        """设置当前选中的菜单项"""
        if 0 <= index < self.menu_list.count():
            self.menu_list.setCurrentRow(index)

    def resizeEvent(self, event):
        """重写窗口大小事件，动态调整宽度"""
        super().resizeEvent(event)
        # 设置宽度为窗口宽度的5%，最小宽度60px
        new_width = max(80, int(self.parent().width() * 0.05))
        self.setFixedWidth(new_width)
